package easycloud.ecs.ui;

import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import javax.swing.table.AbstractTableModel;

import org.apache.commons.lang.ArrayUtils;

import easycloud.ecs.api.IProvider;
import easycloud.ecs.config.ProviderStatistics;

public class ProviderTableModel extends AbstractTableModel implements Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7995888577108788176L;

	private IProvider[] providers;

	private ProviderStatistics[] statistics;

	private String[] columnNames;

	public ProviderTableModel() {
		columnNames = new String[6];
		columnNames[0] = "Provider";
		columnNames[1] = "Status";
		columnNames[2] = "Heads";
		columnNames[3] = "Lists";
		columnNames[4] = "Gets";
		columnNames[5] = "Posts";
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public String getColumnName(int col) {
		return columnNames[col];
	}

	@Override
	public int getRowCount() {
		if (providers != null) {
			return providers.length;
		} else {
			return 0;
		}
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		switch (columnIndex) {
		case 0:
			return providers[rowIndex].getName();
		case 1:
			return providers[rowIndex].ready() == true ? "Ready" : "Not Ready";
		case 2:
			return Integer.valueOf(statistics[rowIndex].getNumberOfHead());
		case 3:
			return Integer.valueOf(statistics[rowIndex].getNumberOfList());
		case 4:
			return Integer.valueOf(statistics[rowIndex].getNumberOfTotalGet());
		case 5:
			return Integer.valueOf(statistics[rowIndex].getNumberOfTotalPost());
		default:
			return null;
		}
	}

	public void setTableContent(Map<String, IProvider> providers) {
		this.providers = new IProvider[providers.size()];
		this.statistics = new ProviderStatistics[providers.size()];
		int index = 0;
		for (IProvider provider : providers.values()) {
			this.providers[index] = provider;
			this.statistics[index] = provider.getProviderStatistics();
			this.statistics[index].addObserver(this);
			index++;
		}
		fireTableDataChanged();
	}

	@Override
	public void update(Observable o, Object arg) {
		ProviderStatistics stat = (ProviderStatistics)o;
		int index = ArrayUtils.indexOf(this.statistics, stat);
		if(index!=-1){
			this.fireTableRowsUpdated(index, index);
		}
	}
}
